<template>
  <div class="app-container">
    <el-card class="park-form-card" shadow="hover">
      <div slot="header" class="card-header">
        <div class="header-content">
          <div class="header-left">
            <i class="el-icon-office-building header-icon"></i>
            <span class="header-title">{{ isEdit ? '修改园区' : '新增园区' }}</span>
          </div>
          <el-button type="text" icon="el-icon-back" @click="cancel" class="back-btn">返回列表</el-button>
        </div>
      </div>
      
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" class="park-form">
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-header">
            <i class="el-icon-info section-icon"></i>
            <span class="section-title">基本信息</span>
          </div>
          <div class="section-content">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="园区名称" prop="parkName">
                  <el-input 
                    v-model="form.parkName" 
                    placeholder="请输入园区名称" 
                    prefix-icon="el-icon-office-building"
                    class="form-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="园区管理人" prop="manager">
                  <el-input 
                    v-model="form.manager" 
                    placeholder="请输入园区管理人" 
                    prefix-icon="el-icon-user"
                    class="form-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="园区简介" prop="parkDescription">
              <el-input 
                v-model="form.parkDescription" 
                type="textarea" 
                :rows="4"
                placeholder="请输入园区简介，详细描述园区的特色、优势等信息..." 
                maxlength="500"
                show-word-limit
                class="form-textarea"
              />
            </el-form-item>
            <div class="contact-info-section">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="联系电话" prop="contactPhone">
                  <el-input 
                    v-model="form.contactPhone" 
                    placeholder="请输入联系电话" 
                    prefix-icon="el-icon-phone"
                    class="form-input"
                  />
                </el-form-item>
              </el-col>
                <el-col :span="12">
                  <el-form-item label="联系人邮箱" prop="contactEmail">
                    <el-input 
                      v-model="form.contactEmail" 
                      placeholder="请输入联系人邮箱" 
                      prefix-icon="el-icon-message"
                      class="form-input email-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="24">
                <el-col :span="12">
                  <el-form-item label="联系人地址" prop="contactAddress">
                    <el-input 
                      v-model="form.contactAddress" 
                      placeholder="请输入联系人地址" 
                      prefix-icon="el-icon-location-information"
                      class="form-input address-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="所属区域" prop="areaId">
                    <el-select
                      v-model="form.areaId"
                      placeholder="请选择所属区域"
                      clearable
                      filterable
                      :loading="optionsLoading"
                      class="form-select"
                    >
                      <el-option
                        v-for="item in areaOptions"
                        :key="item.id"
                        :label="item.areaName"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
            
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="地理位置" prop="location">
                  <el-input 
                    v-model="form.location" 
                    placeholder="请输入地理位置" 
                    prefix-icon="el-icon-location"
                    class="form-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label=" " label-width="140px">
                  <el-button type="primary" plain icon="el-icon-location" @click="mapDialogVisible = true">从地图选择</el-button>
                </el-form-item>
              </el-col>
            </el-row> -->
            
            <el-row :gutter="24">
              <el-col :span="8">
                <el-form-item label="总面积" prop="totalArea">
                  <el-input 
                    v-model="form.totalArea" 
                    placeholder="请输入总面积" 
                    class="form-input"
                    suffix-icon="el-icon-office-building">
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="建筑面积" prop="buildingArea">
                  <el-input 
                    v-model="form.buildingArea" 
                    placeholder="请输入建筑面积" 
                    class="form-input"
                    suffix-icon="el-icon-office-building">
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="可出租面积" prop="rentedArea">
                  <el-input 
                    v-model="form.rentedArea" 
                    placeholder="请输入可出租面积" 
                    class="form-input"
                    suffix-icon="el-icon-office-building">
                    <template slot="append">m²</template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="出租单价" prop="rentalPrice">
                  <el-input 
                    v-model="form.rentalPrice" 
                    placeholder="请输入出租单价" 
                    class="form-input"
                    suffix-icon="el-icon-money">
                    <template slot="append">元/m²</template>
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="isRecommend">
                  <div class="recommend-switch">
                    <el-switch
                      v-model="form.isRecommend"
                      :active-value="1"
                      :inactive-value="0"
                      active-text="推荐"
                      inactive-text="不推荐"
                      active-color="#67C23A"
                      inactive-color="#F56C6C"
                    />
                    <div class="switch-tip-container">
                      <span class="switch-tip">{{ form.isRecommend === 1 ? '·该园区将在核心园区列表中显示' : '·该园区不会在核心园区列表中显示' }}</span>
                      <span class="switch-tip">·每个区域只能有一个核心园区</span>
                    </div>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
                    <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input
                    v-model="form.longitude"
                    placeholder="请输入经度，例如 116.4074"
                    prefix-icon="el-icon-location"
                    class="form-input"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input
                    v-model="form.latitude"
                    placeholder="请输入纬度，例如 39.9042"
                    prefix-icon="el-icon-location"
                    class="form-input"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="层高" prop="floorHeight">
                  <el-input 
                    v-model="form.floorHeight" 
                    placeholder="请输入层高" 
                    class="form-input">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="Banner页面" prop="bannerPage">
                  <el-select
                    v-model="form.bannerPage"
                    placeholder="请选择Banner页面"
                    clearable
                    filterable
                    :loading="optionsLoading"
                    class="form-select"
                  >
                    <el-option
                      v-for="(item, index) in bannerPageOptions"
                      :key="index"
                      :label="item"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        
        <!-- 配置信息 -->
        <div class="form-section">
          <div class="section-header">
            <i class="el-icon-setting section-icon"></i>
            <span class="section-title">配置信息</span>
          </div>
          <div class="section-content">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="园区标签" prop="parkTags">
                  <el-select
                    v-model="form.parkTags"
                    multiple
                    filterable
                    clearable
                    placeholder="请选择园区标签"
                    class="form-select"
                    :loading="optionsLoading"
                    value-key="tagId"
                  >
                    <el-option
                      v-for="item in parkTagsOptions"
                      :key="item.tagId"
                      :label="item.tagName"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="仓库类型" prop="warehouseTypes">
                  <el-select
                    v-model="form.warehouseTypes"
                    multiple
                    filterable
                    clearable
                    placeholder="请选择仓库类型"
                    class="form-select"
                    :loading="optionsLoading"
                    value-key="typeId"
                  >
                    <el-option
                      v-for="item in warehouseTypeOptions"
                      :key="item.typeId"
                      :label="item.typeName"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="硬件配置" prop="hardwareConfig">
                  <el-select
                    v-model="form.hardwareConfig"
                    multiple
                    filterable
                    clearable
                    placeholder="请选择硬件配置"
                    class="form-select"
                    :loading="optionsLoading"
                    value-key="configId"
                  >
                    <el-option
                      v-for="item in hardwareConfigOptions"
                      :key="item.configId"
                      :label="item.configName"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="园区服务" prop="parkServices">
                  <el-select
                    v-model="form.parkServices"
                    multiple
                    filterable
                    clearable
                    placeholder="请选择园区服务"
                    class="form-select"
                    :loading="optionsLoading"
                    value-key="serviceId"
                  >
                    <el-option
                      v-for="item in parkServiceOptions"
                      :key="item.serviceId"
                      :label="item.serviceName"
                      :value="item"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        
        <!-- 图片上传 -->
        <div class="form-section">
          <div class="section-header">
            <i class="el-icon-picture section-icon"></i>
            <span class="section-title">园区图片</span>
          </div>
          <div class="section-content">
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="缩略图" prop="thumbnailUrl">
                  <EditImage
                    v-model="form.thumbnailUrl"
                    :cropper-config="{
                      autoCrop: true,
                      autoCropWidth: 375,
                      autoCropHeight: 210,
                      fixedBox: false,
                      outputType: 'png'
                    }"
                    :dialog-width="'800px'"
                    :cropper-height="450"
                    upload-tip="支持 JPG、PNG 格式，建议尺寸 375x210，文件大小不超过 5MB"
                    placeholder-text="请上传园区缩略图，建议尺寸 375x210 像素"
                    cropper-title="园区图片裁剪"
                    :max-file-size="5"
                    @image-cropped="onImageCropped"
                    @image-removed="onImageRemoved"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="海报图" prop="posterUrl">
                  <EditImage
                    v-model="form.posterUrl"
                    :cropper-config="{
                      autoCrop: true,
                      autoCropWidth: 750,
                      autoCropHeight: 300,
                      fixedBox: false,
                      outputType: 'png'
                    }"
                    :dialog-width="'800px'"
                    :cropper-height="450"
                    upload-tip="支持 JPG、PNG 格式，建议尺寸 750x300，文件大小不超过 5MB"
                    placeholder-text="请上传园区海报图，建议尺寸 750x300 像素"
                    cropper-title="园区海报裁剪"
                    :max-file-size="5"
                    @image-cropped="onPosterImageCropped"
                    @image-removed="onPosterImageRemoved"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button 
            type="primary" 
            @click="submitForm" 
            :loading="submitLoading" 
            icon="el-icon-check"
            size="medium"
            class="submit-btn">
            {{ isEdit ? '修 改' : '确 定' }}
          </el-button>
          <el-button 
            @click="cancel" 
            icon="el-icon-close"
            size="medium"
            class="cancel-btn">
            取 消
          </el-button>
          <el-button 
            @click="resetForm" 
            icon="el-icon-refresh"
            size="medium"
            class="reset-btn">
            重 置
          </el-button>
        </div>

        <!-- 地图选择弹窗 -->
        <TencentMapPicker
          v-model="mapDialogVisible"
          :initial-longitude="form.longitude"
          :initial-latitude="form.latitude"
          :initial-address="form.location"
          @confirm="onMapPicked"
        />
      </el-form>
    </el-card>


  </div>
</template>

<script>
import { addPark, updatePark, getPark, uploadParkFile } from "@/api/system/park"
import { listPark_tags } from "@/api/system/park_tags";
import { listWarehouse_type } from "@/api/system/warehouse_type";
import { listPark_service } from "@/api/system/park_service";
import { listPark_config } from "@/api/system/park_config";
import { listArea } from "@/api/system/area";
import { listBannerPage } from "@/api/system/banner";
import EditImage from "@/components/EditImage/EditImage.vue"
import TencentMapPicker from "@/components/Map/TencentMapPicker.vue"
import { BASE_FILE_URL } from '@/utils/constants'

export default {
  name: "ParkAdd",
  components: { EditImage, TencentMapPicker },
  data() {
    return {
      // 文件服务器基础URL
      BASE_FILE_URL: BASE_FILE_URL,
      // 提交加载状态
      submitLoading: false,
      // 是否为编辑模式
      isEdit: false,
      // 编辑的园区ID
      editId: null,
      // 表单参数
      form: {
        parkId: null,
        parkName: null,
        parkDescription: null,
        parkTags: [],
        totalArea: null,
        buildingArea: null,
        warehouseTypes: [],
        hardwareConfig: [],
        location: null,
        longitude: null,
        latitude: null,
        parkServices: [],
        rentedArea: null,
        rentalPrice: null,
        floorHeight: null,
        manager: null,
        contactPhone: null,
        contactEmail: null,
        contactAddress: null,
        areaId: null,
        thumbnailUrl: null,
        posterUrl: null,
        bannerPage: null,
        isRecommend: 1
      },
      // 表单校验
      rules: {
        parkName: [
          { required: true, message: "园区名称不能为空", trigger: "blur" },
          { min: 2, max: 50, message: "园区名称长度在 2 到 50 个字符", trigger: "blur" }
        ],
        parkDescription: [
          { required: true, message: "园区简介不能为空", trigger: "blur" },
          { min: 10, max: 500, message: "园区简介长度在 10 到 500 个字符", trigger: "blur" }
        ],
        totalArea: [
          { required: true, message: "总面积不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "总面积必须为正整数", trigger: "blur" }
        ],
        buildingArea: [
          { required: true, message: "建筑面积不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "建筑面积必须为正整数", trigger: "blur" }
        ],
        location: [
          { required: true, message: "地理位置不能为空", trigger: "blur" },
          { min: 5, max: 100, message: "地理位置长度在 5 到 100 个字符", trigger: "blur" }
        ],
        longitude: [
          { pattern: /^-?(?:180(?:\\.0{1,6})?|(?:1[0-7]\\d|\\d{1,2})(?:\\.\\d{1,6})?)$/, message: "经度范围 -180 ~ 180，最多6位小数", trigger: "blur" }
        ],
        latitude: [
          { pattern: /^-?(?:90(?:\\.0{1,6})?|(?:[0-8]?\\d)(?:\\.\\d{1,6})?)$/, message: "纬度范围 -90 ~ 90，最多6位小数", trigger: "blur" }
        ],
        rentedArea: [
          { required: true, message: "可出租面积不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*$/, message: "可出租面积必须为正整数", trigger: "blur" }
        ],
        rentalPrice: [
          { required: true, message: "出租单价不能为空", trigger: "blur" },
          { pattern: /^[0-9]\d*(\.\d{1,2})?$/, message: "出租单价必须为正数，最多保留两位小数", trigger: "blur" }
        ],
        manager: [
          { required: true, message: "园区管理人不能为空", trigger: "blur" },
          { min: 2, max: 20, message: "园区管理人姓名长度在 2 到 20 个字符", trigger: "blur" }
        ],
        contactPhone: [
          { required: true, message: "联系电话不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号码", trigger: "blur" }
        ],
        contactEmail: [
          { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, message: "请输入正确的邮箱格式", trigger: "blur" }
        ],
        contactAddress: [
          { max: 200, message: "联系人地址长度不能超过200个字符", trigger: "blur" }
        ],
        areaId: [
          { required: true, message: "所属区域不能为空", trigger: "blur" }
        ]
      },
      // 下拉选项
      parkTagsOptions: [],
      warehouseTypeOptions: [],
      parkServiceOptions: [],
      hardwareConfigOptions: [],
      areaOptions: [],
      bannerPageOptions: [],
      // 下拉选项加载状态
      optionsLoading: false,
      // 用于暂存裁剪后的图片blob
      croppedImageBlob: null,
      posterCroppedImageBlob: null,
      // 地图选择弹窗
      mapDialogVisible: false
    }
  },
  async created() {
    try {
      // 先获取下拉选项数据
      await this.getDictOptions()
      
      // 检查是否为编辑模式
      const parkId = this.$route.query.id
      if (parkId) {
        this.isEdit = true
        this.editId = parkId
        await this.getParkData(parkId)
      }
    } catch (error) {
      console.error('页面初始化失败:', error)
      this.$modal.msgError('页面初始化失败: ' + error.message)
    }
  },
  methods: {
    /** 获取下拉选项数据 */
    async getDictOptions() {
      if (this.optionsLoading) return;
      
      this.optionsLoading = true;
      try {
        const [parkTagsRes, warehouseTypeRes, parkServiceRes, parkConfigRes, areaRes, bannerPageRes] = await Promise.all([
          listPark_tags({tagType: 0}),
          listWarehouse_type(),
          listPark_service(),
          listPark_config(),
          listArea(),
          listBannerPage()
        ]);

        // 处理园区标签选项
        this.parkTagsOptions = parkTagsRes.rows;
        // 处理仓库类型选项
        this.warehouseTypeOptions = warehouseTypeRes.rows;

        // 处理园区服务选项
        this.parkServiceOptions = parkServiceRes.rows;

        // 处理硬件配置选项
        this.hardwareConfigOptions = parkConfigRes.rows;
        // 处理区域选项
        this.areaOptions = areaRes.rows;
        // 处理Banner页面选项
        this.bannerPageOptions = bannerPageRes.data || [];
      } catch (error) {
        console.error('获取下拉选项数据失败:', error);
        this.$modal.msgError('获取下拉选项数据失败: ' + error.message);
      } finally {
        this.optionsLoading = false;
      }
    },
    
    /** 处理多选字段数据 */
    processMultiSelectField(fieldValue, idKey = 'id') {
      if (Array.isArray(fieldValue)) {
        return fieldValue.map(item => item[idKey] || item.id || item);
      } else if (typeof fieldValue === 'string') {
        try {
          const parsed = JSON.parse(fieldValue);
          return Array.isArray(parsed) ? parsed : [];
        } catch (e) {
          return fieldValue.split(',').filter(Boolean);
        }
      }
      return [];
    },
    
    /** 获取园区详情 */
    async getParkData(parkId) {
      try {
        const res = await getPark(parkId);
        if (res && res.data) {
          // 先保存原始数据
          this.form = res.data;
          
          console.log('园区详情数据:', this.form);
        } else {
          this.$modal.msgError("获取园区详情失败");
        }
      } catch (error) {
        console.error('获取园区详情失败:', error);
        this.$modal.msgError("获取园区详情失败: " + error.message);
      }
    },
    // EditImage组件回调方法
    onImageCropped(blob, base64Url) {
      this.croppedImageBlob = blob
      console.log('缩略图裁剪完成:', blob, base64Url)
    },
    onImageRemoved() {
      this.croppedImageBlob = null
      console.log('缩略图已删除')
    },
    onPosterImageCropped(blob, base64Url) {
      this.posterCroppedImageBlob = blob
      console.log('海报裁剪完成:', blob, base64Url)
    },
    onPosterImageRemoved() {
      this.posterCroppedImageBlob = null
      console.log('海报已删除')
    },
    /** 地图选择回调 */
    onMapPicked({ longitude, latitude, address }) {
      this.form.longitude = Number(longitude)
      this.form.latitude = Number(latitude)
      if (!this.form.location) {
        this.form.location = address || this.form.location
      }
    },
   


    /** 处理图片上传响应数据 */
    processImageUploadResponse(res) {
      if (!res || res.code !== 200) {
        throw new Error(res?.msg || '图片上传失败')
      }
      
      // 根据返回的数据结构，优先使用 fileName，如果没有则使用 url
      let imageUrl = res.fileName || res.url || res.newFileName
      
      // 验证返回的数据完整性
      if (!imageUrl) {
        throw new Error('图片上传成功但未返回有效的文件路径')
      }
      
      // 如果 fileName 是相对路径，需要拼接完整的URL
      if (imageUrl && !imageUrl.startsWith('http') && !imageUrl.startsWith('data:')) {
        if (imageUrl.startsWith('/')) {
          // 如果是绝对路径，直接使用
          imageUrl = imageUrl
        } else {
          // 如果是相对路径，拼接基础URL
          imageUrl = this.BASE_FILE_URL + imageUrl
        }
      }
      
      return imageUrl
    },

    /** 验证图片上传结果 */
    validateImageUpload(imageUrl, imageType = '图片') {
      if (!imageUrl) {
        this.$modal.msgError(`${imageType}上传失败：未获取到有效的文件路径`)
        return false
      }
      
      // 检查URL格式
      if (!imageUrl.startsWith('http') && !imageUrl.startsWith('/') && !imageUrl.startsWith('data:')) {
        this.$modal.msgError(`${imageType}上传失败：文件路径格式不正确`)
        return false
      }
      
      return true
    },

    /** 记录图片上传日志 */
    logImageUpload(imageType, result, error = null) {
      const logData = {
        timestamp: new Date().toISOString(),
        imageType,
        success: !error,
        result: error ? null : result,
        error: error ? error.message : null
      }
      
      console.log(`图片上传日志 [${imageType}]:`, logData)
      
      // 可以在这里添加更多的日志记录逻辑，比如发送到服务器
      if (error) {
        console.error(`图片上传失败 [${imageType}]:`, error)
      } else {
        console.info(`图片上传成功 [${imageType}]:`, result)
      }
    },

    /** 通用图片上传方法 */
    async uploadImage(imageBlob, fileName, uploadType = 2, loadingText = '正在上传图片...') {
      if (!imageBlob) {
        return null;
      }
      
      // 检查图片大小（5MB限制）
      const maxSize = 5 * 1024 * 1024; // 5MB
      if (imageBlob.size > maxSize) {
        this.$modal.msgError(`图片大小不能超过 5MB，当前大小: ${(imageBlob.size / 1024 / 1024).toFixed(2)}MB`)
        return null;
      }
      
      // 检查图片格式
      const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif']
      if (!allowedTypes.includes(imageBlob.type)) {
        this.$modal.msgError('只支持 JPG、PNG、GIF 格式的图片')
        return null;
      }
      
      // 显示上传进度
      const loading = this.$loading({
        lock: true,
        text: loadingText,
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      try {
        const formData = new FormData()
        formData.append('file', imageBlob, fileName)
        formData.append('type', uploadType)
        
        const res = await uploadParkFile(formData)
        const imageUrl = this.processImageUploadResponse(res)
        
        // 记录上传成功日志
        this.logImageUpload(loadingText, res)
        this.$modal.msgSuccess('图片上传成功')
        return imageUrl
      } catch (error) {
        // 记录上传失败日志
        this.logImageUpload(loadingText, null, error)
        this.$modal.msgError("图片上传失败: " + (error.message || '未知错误'))
        throw error
      } finally {
        loading.close()
      }
    },


    /** 提交表单 */
    async submitForm() {
      try {
        const valid = await this.$refs["form"].validate();
        if (!valid) return;
        
        // 添加确认对话框
        try {
          await this.$confirm(`确认${this.isEdit ? '修改' : '提交'}园区信息吗？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
        } catch (error) {
          return // 用户取消
        }

        this.submitLoading = true;
        
        // 创建表单数据副本，避免修改原始表单数据
        const submitData = { ...this.form }
        
        // 处理图片上传（新增或修改时）
        try {
          // 上传缩略图
          if (this.croppedImageBlob) {
            const thumbnailUrl = await this.uploadImage(
              this.croppedImageBlob, 
              'park.png', 
              2, 
              '正在上传缩略图...'
            )
            if (thumbnailUrl && this.validateImageUpload(thumbnailUrl, '缩略图')) {
              submitData.thumbnailUrl = thumbnailUrl
            } else {
              return // 验证失败，停止提交
            }
          }
          
          // 上传海报图
          if (this.posterCroppedImageBlob) {
            const posterUrl = await this.uploadImage(
              this.posterCroppedImageBlob, 
              'park-poster.png', 
              2, 
              '正在上传海报图...'
            )
            if (posterUrl && this.validateImageUpload(posterUrl, '海报图')) {
              submitData.posterUrl = posterUrl
            } else {
              return // 验证失败，停止提交
            }
          }
        } catch (error) {
          console.error('图片上传失败:', error)
          this.$modal.msgError("图片上传失败，请重试")
          return
        }
        
        // 多选字段转为对象数组
        const toIdObjects = (arr, idKey) => Array.isArray(arr) ? arr.map(item => ({ [idKey]: item && item[idKey] !== undefined ? item[idKey] : item })) : arr;
        submitData.parkTags = toIdObjects(submitData.parkTags, 'tagId')
        submitData.warehouseTypes = toIdObjects(submitData.warehouseTypes, 'typeId')
        submitData.hardwareConfig = toIdObjects(submitData.hardwareConfig, 'configId')
        submitData.parkServices = toIdObjects(submitData.parkServices, 'serviceId')

        // isRecommend转数字，默认1
        submitData.isRecommend = submitData.isRecommend === undefined || submitData.isRecommend === null ? 1 : Number(submitData.isRecommend)
        
        if (this.isEdit) {
          await updatePark(submitData)
          this.$modal.msgSuccess("修改成功")
        } else {
          await addPark(submitData)
          this.$modal.msgSuccess("新增成功")
        }
        
        // 返回列表页
        this.$router.back()
      } catch (error) {
        console.error('提交失败:', error)
        this.$modal.msgError("提交失败: " + (error.message || '未知错误'))
      } finally {
        this.submitLoading = false
      }
    },
    /** 取消操作 */
    cancel() {
      this.$router.back()
    },
    /** 重置表单 */
    resetForm() {
      this.$refs["form"].resetFields()
      // 重置表单数据到初始状态
      this.form = {
        parkId: null,
        parkName: null,
        parkDescription: null,
        parkTags: [],
        totalArea: null,
        buildingArea: null,
        warehouseTypes: [],
        hardwareConfig: [],
        location: null,
        longitude: null,
        latitude: null,
        parkServices: [],
        rentedArea: null,
        rentalPrice: null,
        floorHeight: null,
        manager: null,
        contactPhone: null,
        contactEmail: null,
        contactAddress: null,
        areaId: null,
        thumbnailUrl: null,
        posterUrl: null,
        bannerPage: null,
        isRecommend: 1
      }
      // 清空裁剪的图片
      this.croppedImageBlob = null
      this.posterCroppedImageBlob = null
      this.mapDialogVisible = false
      
      this.$modal.msgSuccess("表单已重置")
    },

    

  }
}
</script>

<style scoped lang="scss">
// 主容器样式
.app-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

// 卡片样式
.park-form-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  border: none;
  
  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    transition: box-shadow 0.3s ease;
  }
}

// 卡片头部样式
.card-header {
  background: #409eff;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
  margin: -20px -20px 20px -20px;
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .header-icon {
        font-size: 24px;
        color: #fff;
      }
      
      .header-title {
        font-size: 20px;
        font-weight: 600;
        color: #fff;
        margin: 0;
      }
      
      .status-tag {
        margin-left: 8px;
        border: none;
        font-weight: 500;
      }
    }
    
    .back-btn {
      color: #fff;
      font-weight: 500;
      padding: 8px 16px;
      border-radius: 4px;
      transition: all 0.3s ease;
      
      &:hover {
        background: rgba(255, 255, 255, 0.2);
        color: #fff;
      }
    }
  }
}

// 表单样式
.park-form {
  padding: 0;
  
  .form-section {
    margin-bottom: 24px;
    background: #fff;
    border-radius: 6px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    border: 1px solid #e4e7ed;
    
    .section-header {
      background: #f8f9fa;
      padding: 16px 20px;
      display: flex;
      align-items: center;
      gap: 8px;
      border-bottom: 1px solid #e4e7ed;
      
      .section-icon {
        font-size: 16px;
        color: #409eff;
      }
      
      .section-title {
        font-size: 16px;
        font-weight: 600;
        color: #303133;
        margin: 0;
      }
    }
    
    .section-content {
      padding: 24px;
      
      .form-input {
        .el-input__inner {
          border-radius: 4px;
          border: 1px solid #dcdfe6;
          transition: all 0.3s ease;
          
          &:focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
      }
      
      .form-textarea {
        .el-textarea__inner {
          border-radius: 4px;
          border: 1px solid #dcdfe6;
          transition: all 0.3s ease;
          
          &:focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
      }
      
      .form-select {
        width: 100%;
        
        .el-input__inner {
          border-radius: 4px;
          border: 1px solid #dcdfe6;
          transition: all 0.3s ease;
          
          &:focus {
            border-color: #409eff;
            box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
          }
        }
      }
      
      .recommend-switch {
        display: flex;
        align-items: center;
        // gap: 12px;
        .switch-tip-container {
          display: flex;
          flex-direction: column;
          .switch-tip {
          //  height: 14px;
          line-height: 14px;
          font-size: 12px;
          color: #909399;
          // flex: 1;
        }
        }
      }
    }
  }
}



// 操作按钮样式
.form-actions {
  text-align: center;
  margin-top: 32px;
  padding: 24px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  
  .submit-btn {
    background: #409eff;
    border: none;
    padding: 12px 32px;
    font-weight: 500;
    border-radius: 4px;
    margin-right: 16px;
    transition: all 0.3s ease;
    
    &:hover {
      background: #66b1ff;
    }
  }
  
  .cancel-btn {
    background: #f56c6c;
    border: none;
    color: #fff;
    padding: 12px 32px;
    font-weight: 500;
    border-radius: 4px;
    margin-right: 16px;
    transition: all 0.3s ease;
    
    &:hover {
      background: #f78989;
    }
  }
  
  .reset-btn {
    background: #909399;
    border: none;
    color: #fff;
    padding: 12px 32px;
    font-weight: 500;
    border-radius: 4px;
    transition: all 0.3s ease;
    
    &:hover {
      background: #a6a9ad;
    }
  }
}



// 表单验证样式
.el-form-item.is-error .el-input__inner,
.el-form-item.is-error .el-textarea__inner {
  border-color: #f56c6c;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
}

.el-form-item.is-success .el-input__inner,
.el-form-item.is-success .el-textarea__inner {
  border-color: #67c23a;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
}

// 表单标签样式优化
.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

// 必填项标记样式
.el-form-item.is-required .el-form-item__label::before {
  color: #f56c6c;
}

// 输入框聚焦时的效果
.form-input .el-input__inner:focus,
.form-textarea .el-textarea__inner:focus,
.form-select .el-input__inner:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

// 下拉选择框样式优化
.form-select .el-select .el-input__inner {
  cursor: pointer;
}

.form-select .el-select:hover .el-input__inner {
  border-color: #409eff;
}

// 数字输入框样式
.el-input-number {
  width: 100%;
}

.el-input-number .el-input__inner {
  text-align: left;
}

// 开关组件样式优化
.recommend-switch .el-switch {
  margin-right: 8px;
}

.recommend-switch .el-switch__core {
  border-radius: 12px;
}

// 按钮悬停效果
.form-actions .submit-btn:hover,
.form-actions .cancel-btn:hover,
.form-actions .reset-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

// 响应式优化
@media (max-width: 1200px) {
  .form-section .section-content {
    padding: 20px;
  }
  
  .el-row {
    margin-left: -10px !important;
    margin-right: -10px !important;
  }
  
  .el-col {
    padding-left: 10px !important;
    padding-right: 10px !important;
  }
}

@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }
  
  .card-header .header-content {
    flex-direction: column;
    gap: 12px;
    text-align: center;
  }
  
  .form-section .section-content {
    padding: 16px;
  }
  
  .form-actions {
    padding: 16px;
    
    .submit-btn,
    .cancel-btn,
    .reset-btn {
      margin-bottom: 8px;
      width: 100%;
    }
  }
  
  
  
  // 移动端表单标签宽度调整
  .park-form {
    .el-form-item__label {
      width: 120px !important;
    }
  }
}

// 新字段样式优化
.form-input {
  .el-input__inner {
    &:focus {
      border-color: #409eff;
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }
    
    &::placeholder {
      color: #c0c4cc;
      font-size: 14px;
    }
  }
  
  // 邮箱输入框特殊样式
  &.email-input .el-input__inner {
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  }
  
  // 地址输入框特殊样式
  &.address-input .el-input__inner {
    font-size: 14px;
  }
}

// 联系信息区域样式
.contact-info-section {
  .el-form-item {
    margin-bottom: 20px;
    
    .el-form-item__label {
      font-weight: 500;
      color: #606266;
    }
  }
  
  // 联系信息图标样式
  .el-input__prefix {
    color: #409eff;
    font-size: 16px;
  }
}

// 表单验证提示样式优化
.el-form-item.is-error {
  .el-form-item__error {
    color: #f56c6c;
    font-size: 12px;
    line-height: 1.2;
    padding-top: 4px;
  }
}

// 打印样式优化
@media print {
  .app-container {
    background: #fff;
    padding: 0;
  }
  
  .park-form-card {
    box-shadow: none;
    border: 1px solid #ddd;
  }
  
  .form-actions,
  .card-header {
    display: none;
  }
}
</style>
